<template>
  <div class="product-main">
    <el-collapse v-model="activeNames" @change="handleChange">
      <el-collapse-item title="商品管理介绍" name="1">
        <div>
          商品管理模块可以对客户端的商品进行增删改查等相关操作,来控制客户端商品的列表展示和商品详情
        </div>
      </el-collapse-item>
    </el-collapse>
    <!-- form查询 -->
    <el-collapse v-model="activeNames" @change="handleChange" class="card">
      <el-collapse-item title="条件查询" name="1">
        <el-card shadow="never">
          <el-form
            ref="search"
            :model="search"
            :inline="true"
            size="small"
            label-width="80px"
          >
            <el-row :gutter="10">
              <el-col :span="6" :offset="0">
                <el-form-item label="商品名称" size="mini">
                  <el-input
                    v-model="search.name"
                    class="search-input"
                    size="mini"
                    placeholder="商品名称/模糊查询"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6" :offset="0">
                <el-form-item label="商品货号" size="mini">
                  <el-input
                    v-model="search.productSn"
                    class="search-input"
                    size="mini"
                    placeholder="商品货号"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="6" :offset="0">
                <el-form-item label="品牌" size="mini">
                  <el-select
                    v-model="search.brandId"
                    class="search-input"
                    size="mini"
                    clearable
                    placeholder="品牌"
                  >
                    <el-option
                      v-for="item in brandList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6" :offset="0">
                <el-form-item label="上架状态" size="mini">
                  <el-select
                    v-model="search.publishStatus"
                    class="search-input"
                    size="mini"
                    clearable
                    placeholder="上架状态"
                  >
                    <el-option label="上架" value="1" />
                    <el-option label="未上架" value="0" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6" :offset="0">
                <el-form-item label="审核状态" size="mini">
                  <el-select
                    v-model="search.verifyStatus"
                    class="search-input"
                    size="mini"
                    clearable
                    placeholder="审核状态"
                  >
                    <el-option label="审核" value="1" />
                    <el-option label="未审核" value="0" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col style="float: right" :span="4" :offset="0">
                <el-form-item>
                  <el-button @click="doReset">重置</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
      </el-collapse-item>
    </el-collapse>
    <!-- 表格 -->
    <el-card shadow="never" class="card">
      <div slot="header">
        <el-button type="primary" size="small" @click="add">新增</el-button>
        <el-button type="primary" size="small" @click="exportExcel">
          导出商品列表excel文件
        </el-button>
      </div>
      <el-table
        v-loading="loading"
        :data="productList"
        border
        style="width: 100%"
      >
        <el-table-column type="index" label="序号" fixed="left" />

        <!-- 商品列表内容 -->
        <el-table-column label="商品图片" width="150">
          <template slot-scope="scope">
            <img :src="scope.row.pic" class="table_img" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="商品名称" width="350">
          <template slot-scope="scope">
            <p>{{ scope.row.name }}</p>
            <p>品牌: {{ scope.row.brandName }}</p>
            <p>{{ scope.row.description }}</p>
          </template>
        </el-table-column>

        <el-table-column align="center" label="商品价格" width="150">
          <template slot-scope="scope">
            <p>原价: {{ scope.row.originalPrice }}</p>
            <p>现价: {{ scope.row.price }}</p>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          prop="productCategoryName"
          label="商品类别"
          width="150"
        />
        <el-table-column align="center" label="标签" :width="180">
          <template slot-scope="scope">
            <p>
              最新:
              <el-switch
                v-model="scope.row.newStatus"
                size="small"
                :active-value="1"
                :inactive-value="0"
                @change="changeShow('newStatus', scope.row)"
              />
            </p>
            <p>
              推荐:
              <el-switch
                v-model="scope.row.recommendStatus"
                size="small"
                :active-value="1"
                :inactive-value="0"
                @change="changeShow('recommendStatus', scope.row)"
              />
            </p>
          </template>
        </el-table-column>
        <el-table-column align="center" label="标签2" :width="180">
          <template slot-scope="scope">
            <p>
              发布:
              <el-switch
                v-model="scope.row.publishStatus"
                size="small"
                :active-value="1"
                :inactive-value="0"
                @change="changeShow('publishStatus', scope.row)"
              />
            </p>
            <p>
              审核:
              <el-switch
                v-model="scope.row.verifyStatus"
                size="small"
                :active-value="1"
                :inactive-value="0"
                @change="changeShow('verifyStatus', scope.row)"
              />
            </p>
          </template>
        </el-table-column>
        <!-- sku !!! -->
        <el-table-column align="center" prop="keywords" label="sku" width="150">
          <template slot-scope="scope">
            <el-button type="text" size="default" @click="SkuDetail(scope.row)"
              >编辑sku</el-button
            >
          </template>
        </el-table-column>
        <el-table-column align="center" prop="weight" label="重量" width="80" />
        <el-table-column align="center" prop="sort" label="排序" width="150" />

        <el-table-column fixed="right" label="操作" width="100">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="goEdit(scope.row)"
              >编辑</el-button
            >
            <el-button type="text" size="small" @click="goDelete(scope.row)"
              ><span style="color: red">删除</span></el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.currentPage"
        :page-sizes="page.pageSizes"
        :page-size="page.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total"
      />
      <SkuDetail ref="skuDetail" />
    </el-card>
  </div>
</template>

<script>
import productApi from '@/api/product/index'
import brandApi from '@/api/brand/index'
import mixin from '@/mixins/index'
import SkuDetail from '@/views/product/components/skuDetail'
export default {
  components: { SkuDetail },
  mixins: [mixin],

  data() {
    return {
      activeNames: ['1'],
      search: {
        productSn: '',
        publishStatus: '',
        verifyStatus: '',
        brandId: '',
        name: ''
      },
      productList: [],
      brandList: [],
      loading: false,
      sendSearch: {}
    }
  },
  created() {
    this.getProductList()
    this.getBrandList()
  },
  methods: {
    //新增
    add() {
      this.$router.push({ path: '/product/addproductDetail' })
    },
    //修改switch状态
    changeShow(key, item) {
      var id = item.id
      // 暂存状态，修改失败的时候反选回去
      var tempStatus = item[key] === 0 ? 1 : 0
      let str = ''
      // 计算一次 switch 表达式 把表达式的值与每个 case 的值进行对比 如果存在匹配，则执行关联代码
      switch (key) {
        case 'newStatus':
          str = 'switchNewStatus'
          break
        case 'previewStatus':
          str = 'switchPreviewStatus'
          break
        case 'publishStatus':
          str = 'switchPublishStatus'
          break
        case 'recommendStatus':
          str = 'switchRecommendStatus'
          break
        case 'verifyStatus':
          str = 'switchVerifyStatus'
          break
        default:
          break
      }
      productApi[str]({
        productId: id,
        status: item[key]
      })
        .then((res) => {
          if (res.success) {
            this.$message.success('修改状态成功')
          } else {
            item[key] = tempStatus
            this.$message.error('修改状态失败')
          }
        })
        .catch((rej) => {
          item[key] = tempStatus
          this.$message.error('修改状态失败')
        })
    },
    handleChange(val) {
      console.log(val)
    },
    // 编辑skuDetail
    SkuDetail(row) {
      console.log(row)
      console.log(this.$refs.skuDetail)
      this.$refs.skuDetail.openDetail(row.id)
    },
    //获取品牌列表
    getBrandList() {
      brandApi
        .brandList()
        .then((res) => {
          this.brandList = res.data.items
        })
        .catch((rej) => {
          console.log('error', rej)
        })
    },
    //搜索
    doSearch() {
      this.page = this.$options.data().page
      for (const key in this.search) {
        console.log(this.search[key])
        if (this.search[key] || this.search[key] === '') {
          this.sendSearch[key] = this.search[key]
          console.log(this.sendSearch)
        }
      }
      this.getProductList()
    },
    //获取列表信息
    getProductList() {
      productApi
        .productList(this.page.currentPage, this.page.pageSize, this.sendSearch)
        .then((res) => {
          this.productList = res.data.rows
          this.page.total = res.data.total
          this.loading = false
        })
        //捕捉错误
        .catch((rej) => {
          console.log(rej)
          this.loading = false
        })
    },
    //编辑
    goEdit(row) {
      this.$router.push({ name: 'ProductDetail', params: { id: row.id } })
      //  this.$router.push({ path: '/product/productDetail', query: { id: row.id }})
    },
    //删除
    goDelete(row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          productApi
            .productDel(row.id)
            .then((res) => {
              if (res.success) {
                this.getProductList()
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                })
              } else {
                this.$message.error(res.message)
              }
            })
            .catch((res) => {
              this.$message.error(res.message)
            })
        })
        .catch((rej) => {
          console.log(rej)
        })
    },
    exportExcel() {
      import('@/vendor/Export2Excel').then((excel) => {
        console.log(excel);
        const header=['商品名称','商品价格','商品类别']
        const header_key=['name','price','productCategoryName']
        const data =[]
        this.productList.forEach((out)=>{
          var innerArr=[]
          header_key.forEach(inner=>{
            innerArr.push(out[inner])
          })
          data.push(innerArr)
        })
        console.log(data);
        excel.export_json_to_excel({
          header: header, //表头 必填
          data, //具体数据 必填
          filename: '佳豪的商品列表', //非必填
          autoWidth: true, //非必填
          bookType: 'xlsx' //非必填
        })
      })
    },
    //重置
    doReset() {
      this.search = this.$options.data().search
    },
    handleSizeChange(val) {
      this.page.size = val
      this.page.currentPage = 1
      this.getProductList()
    },
    handleCurrentChange(val) {
      this.page.currentPage = val
      this.getProductList()
    }
  }
}
</script>

<style scoped lang="scss">
.product-main {
  background-color: #f0f2f5;
  .card {
    margin: 30px;
  }
  .table_img {
    width: 100px;
    height: 100px;
  }
}
</style>